﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace Chinaer.Core.Helper
{
    public class GenerateTokenIDHelper
    {
        private static string tokenKey = string.Empty;
        /// <summary>
        /// 生成TOken
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static string GenerateToken(string userName)
        {
            if (userName == null)
            {
                return null;
            }

            tokenKey = Chinaer.Core.Helper.ConfigHelper.GetAppSetting("tokenKey");
            if (tokenKey == null || tokenKey.Trim().Length != 8)
            {
                throw new Exception("密钥必须是八位");
            }
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                byte[] inputByteArray = Encoding.UTF8.GetBytes(userName);
                des.Key = ASCIIEncoding.ASCII.GetBytes(tokenKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(tokenKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Convert.ToBase64String(ms.ToArray());
                ms.Close();
                return str;
            }
        }
        /// <summary>
        /// 解密Token
        /// </summary>
        /// <param name="pToDecrypt"></param>
        /// <returns></returns>
        public static string Decrypt(string pToDecrypt)
        {
            if (tokenKey == null)
            {
                tokenKey = Chinaer.Core.Helper.ConfigHelper.GetAppSetting("tokenKey");
            }
            if (tokenKey == null || tokenKey.Trim().Length != 8)
            {
                throw new Exception("密钥必须是八位");
            }
            byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.Key = ASCIIEncoding.ASCII.GetBytes(tokenKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(tokenKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }
    }
}
